import os
import subprocess


def save_git_diff_with_subprocess(
    branch_a, branch_b, sub_dirs, output_dir="diff_output"
):
    """
    Using subprocess to invoke git commands for saving branch differences

    parameter:
        branch_a: Branch A name
        branch_b: Branch B name
        sub_dirs: List of subdirectories to compare
        output_dir: Output directory (default is 'diff_output')
    """
    # Ensure the output directory exists
    os.makedirs(output_dir, exist_ok=True)

    # traverse each subdirectory
    for sub_dir in sub_dirs:
        cmd = ["git", "diff", branch_a, branch_b, "--", sub_dir]

        result = subprocess.run(
            cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True
        )

        if result.returncode != 0:
            print(f"Error comparing {sub_dir}: {result.stderr}")
            continue

        if result.stdout:
            safe_filename = sub_dir.replace("/", "_").replace("\\", "_") + ".diff"
            output_path = os.path.join(output_dir, safe_filename)

            with open(output_path, "w", encoding="utf-8") as f:
                f.write( f"# Diff between {branch_a} and {branch_b} for directory: {sub_dir}\n\n" )
                f.write(result.stdout)

            print(f"Saved diff for '{sub_dir}' to {output_path}")
        else:
            print(f"No differences found for directory: {sub_dir}")


sub_repo_dirs = [
    "3d_scene_adapter",
    "3d_widget_adapter",
    "kits/js",
    "lume/Lume_3D",
    "lume/Lume_3DText",
    "lume/LumeBase",
    "lume/LumeBinaryCompile",
    "lume/LumeEcsSerializer",
    "lume/LumeEngine",
    "lume/LumeFont",
    "lume/LumeJpg",
    "lume/LumeMeta",
    "lume/LumePng",
    "lume/LumeRender",
    "lume/LumeScene",
]


def main():
    print("Git branch difference analysis tool")
    print("=" * 50)

    # Get user input
    branch_a = input("Please enter the base branch name: ").strip()
    branch_b = input("Please enter the name of the comparison branch: ").strip()

    print("\nGenerating diff file...")
    save_git_diff_with_subprocess(branch_a, branch_b, sub_repo_dirs)


if __name__ == "__main__":
    main()
